﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WAD.WEB.AppCode;
using WAD.Model;
using WAD.DAL;
using System.Text;
using System.Drawing;
using GL.Tools;

namespace WAD.WEB.Client.Ajax
{
    /// <summary>
    /// Article 的摘要说明
    /// </summary>
    public class Shared : AjaxBase
    {
        public override void AjaxMethodDispatch(String identity)
        {
            switch (identity)
            {
                case "add": this.Add(); break;
                case "remove": this.Remove(); break;
                case "getlist": this.GetList(); break;
            }
        }
        /// <summary>
        /// 添加
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Add()
        {
            IsLogin();
            int aduser_id = Parse.Int("aduser_id", 0);
            int adp_id = Parse.Int("adp_id", 0);   //上级ID
            int advertId = Parse.Int("advert_id", 0);//广告id
            int articleId = Parse.Int("article_id", 0);//文章id
            int type = Parse.Int("type", 1);//分享类型
            int shareid = Parse.Int("shareid", 0);  //别人的分享ID
            string url = HttpUtility.UrlDecode(Parse.String("url", ""));//分享的链接
            string urllogo = HttpUtility.UrlDecode(Parse.String("url_logo", ""));//分享的链接
            string title = Parse.String("url_title", "");//分享的链接
            string logo = HttpUtility.UrlDecode(Parse.String("logo"));
            string[] arrAD = Parse.StringSplit("advert_ids", ",");

            if (advertId < 1)
                ParamError();
            
            title = HttpUtility.UrlDecode(title);
            if (title.Length > 50)
                title = title.Substring(0, 50);

            StringBuilder sbAD = new StringBuilder();
            if (arrAD != null)
            {
                for (int i = 0, j = 0; i < arrAD.Length; i++)
                {
                    if (string.IsNullOrEmpty(arrAD[i]) || j > 2)
                        continue;
                    if (sbAD.Length > 0)
                        sbAD.Append(",");
                    sbAD.Append(arrAD[i]);
                    j++;
                }
            }

            String advert_ids = sbAD.ToString();

            //根据ID，获取title,url
            if (shareid > 0)
            {
                MShared model = GetDetail(shareid);
                title = model.url_title;
                url = model.url;
                articleId = model.article_id.Value;

                if (model.type.Value == 2)
                    urllogo = model.url_logo;   //外链LOGO
            }

            if (articleId < 1 && string.IsNullOrEmpty(url))
                ParamError();

            //广告用户=当前登录用户,才允许添加记录
            if (aduser_id != UserId)
            {
                //广告发布者ID != parent用户ID
                if (adp_id > 0 && aduser_id == adp_id) { }
                else
                    JsonResult(0, "不能更换别人的广告");
            }

            //获取用户所有套餐
            List<Dictionary<string, object>> list = DaoUserVersion.GetList(UserId);
            int group = 0;    //免费
            for (int i = 0; i < list.Count; i++)
            {
                object end_date = list[i]["end_date"];
                if (Convert.ToDateTime(end_date).Subtract(DateTime.Now).TotalDays > 0)
                    group = 1;  //未过期
                else
                    group = 2; // 过期
            }

            if (group == 2)
                JsonResult(500, "您的账号已过期，续费后才能使用");

            //int count = DaoShared.SharedCount(group, UserId, advertId, articleId, url);
            //if (count == 1)
            //    JsonResult(0, "不允许重复添加");
            //else if (count > 1)
            //    JsonResult(1, "请升级版本");//分享数是否 > 1

            int maxid = DaoShared.IsAdd(group, UserId, advertId, articleId, url, advert_ids);
            if (maxid > 0)
                JsonResult(0, "不允许重复添加", maxid);   //id>0 表示有记录存在
            else if (group == 0 && maxid == -500)
                JsonResult(500, "免费版请升级后试用");
            else if (maxid == -500)
                JsonResult(500, "创建分享链接异常");    //校验异常   
            else if (maxid == 0) { }                   //校验通过

            MShared m = new MShared() { advert_id = advertId, type = type, user_id = UserId, url = "", advert_ids = advert_ids };
            if (type == 1)
            {
                m.article_id = articleId;
            }
            else if (type == 2)
            {
                m.article_id = 0;
                m.url = url;
                m.url_title = title;
                m.url_logo = urllogo;
                

                //网络图片先下载到本地
                if (urllogo.StartsWith("http"))
                {

                    //订阅号图片必须删除参数  否则下载的图片显示不正常
                    if (urllogo.IndexOf("://mmbiz.qpic.cn") != -1 && urllogo.IndexOf("?") != -1)
                    {
                        urllogo = urllogo.Substring(0, urllogo.IndexOf("?"));
                    }

                    //文件名
                    String name = DateTime.Now.ToString("yyyyMMddHHmmss") + StringHelper.Random(6) + ".jpg";

                    //Url访问的文件夹
                    String urlDir = String.Empty;

                    String dateStr = DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/";

                    //绝对路径文件夹
                    String jdDir = HttpContext.Current.Server.MapPath(WJXConfig.Path.IMAGE + dateStr);

                    //文件夹不存在创建文件夹
                    if (!System.IO.Directory.Exists(jdDir))
                    {
                        System.IO.Directory.CreateDirectory(jdDir);
                    }

                    bool flag = HttpTool.SavaFile(urllogo, jdDir + name);
                    if (flag)
                    {
                        //裁剪成需要的尺寸大小  微信图片裁剪时在server2003上会报错
                        if (ImageUtil.Cut(jdDir + name, jdDir + "md_" + name, 300, 300, true))
                        {
                            m.url_logo = WJXConfig.Path.IMAGE + dateStr + "md_" + name;
                        }
                        else
                        {
                            m.url_logo = WJXConfig.Path.IMAGE + dateStr + name;

                        }
                    }
                }
            }

            //if (m.url_logo != "" && m.url_logo != null && m.url_logo.ToLower().Contains("http"))
            //{
            //    m.url_logo = Upload(m.url_logo);
            //}


            int id = DaoShared.Add(m);
            if (id > 0)
                JsonResult(0, "", id);

            Fail();
        }


        /// <summary>
        /// 移除分享
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Remove()
        {
            IsLogin();
            int id = Parse.Int("id", 0);
            int article_id = Parse.Int("article_id", 0);
            if (id == 0)
            {
                ParamError();
            }

            if (DaoShared.Hide(id, UserId))
            {
                if (article_id > 0)
                    DaoArticle.Hide(article_id, UserId);    //隐藏原创文章
                Success();
            }
            else
            {
                Fail();
            }
        }


        /// <summary>
        /// 获取分享列表
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetList()
        {
            IsLogin();
            int pageIndex = Parse.Int("page_index", 1);//当前页
            bool isOther = Parse.Boolean("is_other", false);

            PageData pg = DaoShared.GetList(pageIndex, 20, UserId, isOther);

            if (pg.itemCount == 0)
            {
                DataEmpty();
            }
            else
            {
                int userid = Parse.Int("user_id", 0);
                if (userid > 0)
                {
                    //获取用户自定义封面
                    Dictionary<string, object> model = DaoUser.GetDetail(userid, "articlelogo");
                    for (int i = 0; i < pg.table.Rows.Count; i++)
                    {
                        if (Convert.ToString(pg.table.Rows[i]["url_logo"]) == "")
                        {
                            if (model != null && model["articlelogo"] != DBNull.Value)
                                pg.table.Rows[i]["url_logo"] = model["articlelogo"];
                        }
                    }
                }
                Success(pg);
            }
        }

        public string Upload(string url)
        {
            Bitmap bm = HttpTool.Get_img(url);

            bm = HttpTool.KiResizeImage(bm, 300, 300);
            String dateStr = DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/";
            string path = WJXConfig.Path.IMAGE;
            path += dateStr;

            //绝对路径文件夹
            String jdDir = HttpContext.Current.Server.MapPath(path);
            string guid = System.Guid.NewGuid().ToString();
            //文件夹不存在创建文件夹
            if (!System.IO.Directory.Exists(jdDir))
            {
                System.IO.Directory.CreateDirectory(jdDir);
            }

            bm.Save(jdDir + guid + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            return path + guid + ".jpg";
        }


        MShared GetDetail(int sharedid)
        {
            return DaoShared.GetInfo(sharedid);
        }

    }
}